package onlyJava;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;

public class JpegByteCompressor {

    /**
     * 压缩 JPG 图片（纯 Java，无第三方依赖）
     *
     * @param imageBytes 原始图片字节数组
     * @param quality    压缩质量 (0.0 ~ 1.0)
     * @return 压缩后的字节数组
     */
    public static byte[] compressJpegBytes(byte[] imageBytes, float quality) throws IOException {
        if (imageBytes == null || imageBytes.length == 0) {
            throw new IllegalArgumentException("Input image bytes cannot be null or empty");
        }

        if (quality < 0f || quality > 1f) {
            throw new IllegalArgumentException("Quality must be between 0.0 and 1.0");
        }

        // 读取字节为 BufferedImage
        BufferedImage image;
        try (ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes)) {
            image = ImageIO.read(bais);
        }

        if (image == null) {
            throw new IOException("Invalid image data, cannot decode image");
        }

        // 获取 JPG 写入器
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
        if (!writers.hasNext()) {
            throw new IllegalStateException("No ImageWriter found for format: jpg");
        }
        ImageWriter writer = writers.next();

        // 设置压缩参数
        ImageWriteParam param = writer.getDefaultWriteParam();
        if (param.canWriteCompressed()) {
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(quality); // 设置压缩质量 (0.0 = 最差, 1.0 = 最好)
        }

        // 输出到字节流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (ImageOutputStream ios = ImageIO.createImageOutputStream(baos)) {
            writer.setOutput(ios);
            writer.write(null, new IIOImage(image, null, null), param);
        } finally {
            writer.dispose();
        }

        return baos.toByteArray();
    }

    // 测试代码
    public static void main(String[] args) throws IOException {
        byte[] original = java.nio.file.Files.readAllBytes(new File("test.jpg").toPath());
        byte[] compressed = compressJpegBytes(original, 0.3f); // 压缩到30%质量
        java.nio.file.Files.write(new File("test_compressed.jpg").toPath(), compressed);
        System.out.println("压缩完成！");
    }
}
